<?php
include ("../main/inc/global.inc.php");

require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
require_once (api_get_path(CONFIGURATION_PATH).'profile.conf.php');

api_block_anonymous_users(); // only users who are logged in can proceed

// Top part of the HTML
Display :: display_header('Upload');

global $_user;
?>

<?php
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$path = "files/";
      
if(!isset($_FILES["file"]))
{
	Display::display_error_message("
		<p>Your file cannot be bigger than " . ini_get('post_max_size') . ". If possible, compress the file before reupload.</p>
		<p><a href=\"#\" onclick=\"javascript:history.go(-1); return false;\">Click here</a> to try again.</p>", false);
}
elseif ($_FILES["file"]["error"] > UPLOAD_ERR_OK)
{
	// Display appropriate message
	$message = "<p>";
	switch($_FILES["file"]["error"])
	{
	case UPLOAD_ERR_INI_SIZE: 
		$message .= "Your file cannot be bigger than " . ini_get('post_max_size') . ". If possible, compress the file before reupload."; 
		break; 
	case UPLOAD_ERR_FORM_SIZE: 
		if(isset($_POST['uploadForm']['MAX_FILE_SIZE']))
			$maxSize = intval($_POST['uploadForm']['MAX_FILE_SIZE']) . " bytes";
		else
			$maxSize = ini_get('post_max_size');
		$message .= "Your file cannot be bigger than $maxSize. If possible, compress the file before reupload."; 
		break; 
	case UPLOAD_ERR_PARTIAL: 
		$message .= "The uploaded file was only partially uploaded. Please try reuploading your file."; 
		break; 
	case UPLOAD_ERR_NO_FILE: 
		$message .= "No file was uploaded."; 
		break; 
	case UPLOAD_ERR_NO_TMP_DIR: 
		$message .= "Missing a temporary folder."; 
		break; 
	case UPLOAD_ERR_CANT_WRITE: 
		$message .= "Failed to write file to disk. Please contact the manager if you constantly see this error."; 
		break; 
	case UPLOAD_ERR_EXTENSION: 
		$message .= "File upload stopped by an PHP extension."; 
		break; 
		
	default: 
		$message .= "Unknown upload error."; 
		break; 
	}
	$message .= "</p><p><a href=\"#\" onclick=\"javascript:history.go(-1); return false;\">Click here</a> to try again.</p>";
	Display::display_error_message($message, false);
}
else
{
	if ($_FILES["file"]["type"] == "text/plain") {
		$tagArray = explode(',', $_POST['tagArray']);
		$path .= basename($_FILES["file"]["name"]);
		$date = date("Y-m-d H:i:s");
		//insert into table file
		$result = Database::uploadFile($path,$_POST[uploadId],$_POST[tagArray],$date);
		$result2 = Database::getLastFileId();
		$row = $result2[0];
		$fileId = $row['id'];

		//insert into table file_notification
		foreach ($tagArray as &$value) {
		    $result3 = Database::insertFileNotification($fileId,$value);
		    if (!$result3)
		        {
		        die('Error: ' . $result3);
		        }
		}
		// $arr is now array(2, 4, 6, 8)
		unset($value); // break the reference with the last element
		
		mysql_close($link);
		
		if (!$result)
		{
		  die('Error: ' . $result);
		}
		else
		{

		    if (file_exists($path))
		      {
		        Display::display_error_message("<p><strong>" . $_FILES["file"]["name"] . "</strong> already exists. Please rename your file and reupload.</p><p><a href=\"#\" onclick=\"javascript:history.go(-1); return false;\">Click here</a> to try again.</p>", false);
		      }
		    else
		      {
		        $fileName = $_FILES["file"]["name"];
			$result4=Database::insertFileUser($fileId,$_POST["uploadId"]);
		        $uploadResult = move_uploaded_file($_FILES["file"]["tmp_name"], $path);
		        if($uploadResult)
				Display::display_confirmation_message("<p>File <strong>$fileName</strong> uploaded successfully. See <a href=\"FileList.php\">File list</a> here.</p>", false);
			else
				Display::display_warning_message("<p>File <strong>$fileName</strong> not uploaded. Please try again later.</p><p>If you continue to see this message, please contact the manager.</p>", false);

		        //Tag users
		        //print_r($tagArray);
		        if (empty($tagArray) || count($tagArray) == 0)
		        {
		            echo "<p>You didn't tag any user.</p>";
		        }
		        // Is it possible to show all tagged users here?
		        else
		        {
				Display::display_normal_message("<p>You tagged some users. When they are online, they will be notified about your tag.</p>", false);
		        }
		      }
		}
	}
	else
	{
		Display::display_error_message("<p>Only txt file is allowed.</p>", false);
	}
  }

?>
<?php
// Footer
Display :: display_footer();
?>
